package com.sci.web.util;

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.Graphics;
import java.awt.color.ColorSpace;
import javax.imageio.ImageIO;
public class ImageCutUtil {


	public static void scale(String srcImageFile, double standardWidth,
	    double standardHeight) {
	   try {
	    System.out.println("scale&&&&&&&&&&&&&");
	    BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件

	    Image image = src.getScaledInstance((int) standardWidth,
	      (int) standardHeight, Image.SCALE_DEFAULT);
	    BufferedImage tag = new BufferedImage((int) standardWidth,
	      (int) standardHeight, BufferedImage.TYPE_INT_RGB);
	    Graphics g = tag.getGraphics();
	    g.drawImage(image, 0, 0, null);
	    g.dispose();
	    ImageIO.write(tag, "JPG", new File(srcImageFile + "name.JPG"));// 输出到文件流
	   } catch (IOException e) {
	    e.printStackTrace();
	   }
	}

	public static void cut(String srcImageFile, double standardWidth,
	    double standardHeight) {
	   try {
	    Image img;
	    ImageFilter cropFilter;
	    // 读取源图像
	    BufferedImage bi = ImageIO.read(new File(srcImageFile));
	    int srcWidth = bi.getWidth(); // 源图宽度
	    int srcHeight = bi.getHeight(); // 源图高度
	    if (srcWidth > standardWidth && srcHeight > standardHeight) {
	     Image image = bi.getScaledInstance(srcWidth, srcHeight,
	       Image.SCALE_DEFAULT);
	     int w = 0;
	     int h = 0;

	     double wScale = srcWidth / standardWidth;
	     double hScale = srcHeight / standardHeight;
	     int srcWidth2;
	     int srcHeight2;
	     if (wScale > hScale) {

	      srcWidth2 = (int) (standardWidth * hScale);
	      w = (srcWidth - srcWidth2) / 2;
	      srcWidth = srcWidth2;
	      h = 0;
	     } else {
	      srcHeight2 = (int) (standardHeight * wScale);
	      h = (srcHeight - srcHeight2) / 2;
	      srcHeight = srcHeight2;
	      w = 0;
	     }

	     cropFilter = new CropImageFilter(w, h, srcWidth, srcHeight);
	     img = Toolkit.getDefaultToolkit().createImage(
	       new FilteredImageSource(image.getSource(), cropFilter));
	     BufferedImage tag = new BufferedImage(srcWidth, srcHeight,
	       BufferedImage.TYPE_INT_RGB);
	     Graphics g = tag.getGraphics();
	     g.drawImage(img, 0, 0, null);
	     g.dispose();
	     ImageIO.write(tag, "JPEG", new File(srcImageFile));
	     scale(srcImageFile, standardWidth, standardHeight);
	    }
	   } catch (Exception e) {
	    e.printStackTrace();
	   }
	}

	public static void main(String[] args) {
	   cut("H:/pic/000.jpg", 200, 229);
	}
}


